package 算法.动态规划;

/**
 * @author Zhu
 * @Description
 * @create 2023-03-13
 */
public class JZ85连续子数组的最大和2 {
    //动态规划
    public int[] FindGreatestSumOfSubArray (int[] array) {
        // write code here
        //记录到下标i为止的最大连续子数组和
        int[] dp = new int[array.length];
        dp[0] = array[0];
        int maxsum = dp[0];
        //滑动区间
        int left = 0, right = 0;
        //记录最长的区间
        int resl = 0, resr = 0;
        for(int i = 1; i < array.length; i++){
            right++;
            //状态转移：连续子数组和最大值
            dp[i] = Math.max(dp[i - 1] + array[i], array[i]);
            //区间新起点
            if(dp[i - 1] + array[i] < array[i])
                left = right;
            //更新最大值
            if(dp[i] > maxsum || dp[i] == maxsum && (right - left + 1) > (resr - resl + 1)){
                maxsum = dp[i];
                resl = left;
                resr = right;
            }
        }
        //取数组
        int[] res = new int[resr - resl + 1];
        for(int i = resl; i <= resr; i++)
            res[i - resl] = array[i];
        return  res;
    }

    //动态规划空间优化
    public int[] FindGreatestSumOfSubArray2 (int[] array) {
        int x = array[0];
        int y = 0;
        int maxsum = x;
        //滑动区间
        int left = 0, right = 0;
        //记录最长的区间
        int resl = 0, resr = 0;
        for(int i = 1; i < array.length; i++) {
            right++;
            //状态转移：连续子数组和最大值
            y = Math.max(x + array[i], array[i]);
            //区间新起点
            if(x + array[i] < array[i])
                left = right;
            //更新最大值
            if(y > maxsum || y == maxsum && (right - left + 1) > (resr - resl + 1)){
                maxsum = y;
                resl = left;
                resr = right;
            }
            //更新x的状态
            x = y;
        }
        //取数组
        int[] res = new int[resr - resl + 1];
        for(int i = resl; i <= resr; i++)
            res[i - resl] = array[i];
        return res;
    }
}
